package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 使用预编译SQL防止SQL注入问题
 */
public class JDBCDemo8 {
    public static void main(String[] args) {
        LoginUserInfo loginUserInfo
                = InputUtil.getInputObject(new LoginUserInfo(),"欢迎登录");

        try (Connection connection = DBUtil.getConnection();){
            String sql = "SELECT id,username,password,nickname,age " +
                         "FROM userinfo " +
                         "WHERE username=? AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);//先将SQL发送给数据库定死语义
            //为两个?设置对应的的值
            ps.setString(1,loginUserInfo.getUsername());
            ps.setString(2,loginUserInfo.getPassword());
            //执行时不再需要传递SQL语句
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                String nickname = rs.getString("nickname");
                System.out.println("登录成功，欢迎回来:"+nickname);
            }else{
                System.out.println("登录失败");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }


    }
}
